$(document).ready(function(){
  var currentUser,
    users = rbiller.config.security.staffUsers;

  function renderUsers(){
    var $list = $("#staffList"),
        html = '',
        key,
        user;

    for (key in users){
      user = users[key];
      html += '<option>' + user.email + '</option>';
    }
    $list.html(html);
  }

  function createUser(email){
    return { 
        email: email,
        authorized: {}
      };
  }

  function addStaffUser(email){
    if (! (email in users )){
      users[email] = createUser(email)
      renderUsers();
      selectStaffUser(email);
    }
  
  }

  function selectStaffUser(email){
    var $userlist = $("#staffList option"),
        user = users[email];

    currentUser = user;


    $userlist.each(function(){
      var $option = $(this),
          checked;
      if ($option.text() === email){
        $option.prop('selected', true);
        $permissions.prop('checked', false);
        $permissions.prop('disabled', false);

        for (activity in currentUser.authorized){
          $checkbox = $permissions.filter('#'+activity);
          checked = user.authorized[activity] === "checked";          
          $checkbox.prop('checked', checked);
        }
      }
    });

  }
  $("#user").autocomplete({
      source: "ajax.php?function=user-search",
      minLength: 2,
      select: function(event,ui){
        var $user = $("#user"),
            email;
        email = ui.item.value;
        if (email) {
          $user.val('');
          addStaffUser(email);
        }
      return false;
      }
    });
  
  $permissions = $("#permissions input");
  $permissions.prop("disabled", true);
  $staffListOptions = $("#staffList option");
  $staffListOptions.on('click',function(){
    var email = $(this).text();
    $permissions.prop("disabled", false); 
    $permissions.prop("checked", false)
    selectStaffUser(email);
    
  });

  $permissions.change(function(){
    var value = $(this).is(":checked"),
        activity = $(this).attr("id");

    if (value) {
      currentUser.authorized[activity] = "checked";
    } else {
      currentUser.authorized[activity] = "";
    }
    $.post("ajax.php?function=setPermission",{
      email: currentUser.email,
      activity: activity,
      value: value
    });
  });

});
